// Server (app.js)
// var express=require(  'express')
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server, { cors: true });

server.listen(3000);
let sockets = []
// app.use(express.static(__dirname+'/dist'))
// app.get('/', function (req, res) {
//   res.sendfile(__dirname + '/dist/index.html');
// });
// app.all('*',function(req,res,next){
//   res.header("Access-Control-Allow-Origin","*")
//   next()
// })
io.on('connection', fn);





function fn(socket) {
   console.log('有人连接');
   let username = null
   socket.on('login', (data) => {

      console.log(data)
      username = data.name
      console.log(username);
      if (!sockets.some(item => item.name == username))
         sockets.push(data)
      else return
      console.log(sockets);
      socket.emit('loginSuccess', sockets)
      io.sockets.emit('receiveMessage', {
         type: 'system', // 系统消息
         msg: `系统消息：用户${username}加入了群聊`
      });
      io.sockets.emit('listenPerson', sockets)
   })
   socket.on('message', (data) => {
      console.log(data);
      io.sockets.emit('receiveMessage', {
         user: data.user,
         msg: data.msg
      });
   })
   socket.on("handleFile",data => {
      //广播给所有用户
      console.log(1);
      io.sockets.emit("receiveImage",data)
    })
   socket.on('disconnect', function () {
      console.log('有人离开了！');
      if (username != null)
         io.sockets.emit('receiveMessage', {
            type: 'system', // 系统消息
            msg: `系统消息：用户${username}离开了群聊`
         });
      sockets = sockets.filter(item => item.name != username)
      io.sockets.emit('listenPerson', sockets)
      console.log(sockets);
   })

}




//防抖
